package result

import (
	"fmt"
	"net/http"
	"private-domain-overseas-service/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"google.golang.org/grpc/status"
)

// HttpResult - 请求返回
func HttpResult(r *http.Request, w http.ResponseWriter, resp interface{}, err error) {
	if err == nil {
		httpx.WriteJson(w, http.StatusOK, xerr.Success(resp))
	} else {
		errCode := xerr.ServiceExceptionError
		errMsg := "服务异常，请稍后重试~"

		causeErr := errors.Cause(err)
		if e, ok := causeErr.(*xerr.CodeError); ok {
			errCode = e.GetErrCode()
			errMsg = e.GetErrMsg()
		} else {
			if gStatus, ok := status.FromError(causeErr); ok {
				errCode = uint32(gStatus.Code())
			}
		}
		logx.WithContext(r.Context()).Errorf("【API-ERR】 : %+v ", err)
		httpx.WriteJson(w, http.StatusOK, xerr.ErrCodeMsg(errCode, errMsg))
	}
}

// HttpErrorResult - 错误请求返回
func HttpErrorResult(r *http.Request, w http.ResponseWriter, err error) {
	errMsg := fmt.Sprintf("%d ,%s", xerr.ServerRequestParamError, err.Error())
	httpx.WriteJson(w, http.StatusOK, xerr.ErrCodeMsg(xerr.ServerRequestParamError, errMsg))
}
